package com.stacker.management.infra.http;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.List;

@Configuration
public class RestTemplateConfig {
    @Bean(name = "stackerRestTemplate")
    public RestTemplate stackerRestTemplate(SimpleClientHttpRequestFactory streamFactory) {
        return new RestTemplate(streamFactory);
    }

    @Bean(name = "streamFactory")
    public SimpleClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
                if (connection instanceof HttpsURLConnection) {
                    ((HttpsURLConnection) connection).setHostnameVerifier((hostname, session) -> true);
                }
                //指定流的大小，当内容达到这个值的时候就把流输出
                if (!httpMethod.equals("GET")) {
                    connection.setChunkedStreamingMode(20 * 1024);
                }
                super.prepareConnection(connection, httpMethod);
            }
        };
        //设置不使用缓存流的形式，假如开启之后，会占用内存来缓存流
        factory.setBufferRequestBody(false);
        factory.setConnectTimeout(150000);
        factory.setReadTimeout(150000);
        return factory;
    }

    @Bean(name = "streamUploadRestTemplate")
    public RestTemplate streamUploadRestTemplate(SimpleClientHttpRequestFactory streamFactory) {
        RestTemplate restTemplate = new RestTemplate(streamFactory);
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> httpMessageConverter : messageConverters) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                // 将默认字符集从"ISO-8859-1"变成"UTF-8"
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
            }
        }

        return restTemplate;
    }
}
